<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页</title>
<!-- 
	<meta http-equiv="refresh" content="0.1;url=/chat/index">
	 -->

<script type="text/javascript" src="../im-web/js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="../im-web/js/jquery.easydrag.handler.beta2.js"></script>
<script type="text/javascript" src="../im-web/js/jquery.overblock-1.2.js"></script>
<script type="text/javascript">
	//var wsuri = "ws://localhost:8080/im-web/websocket2";
	
	var baseUrl = window.location.href;
	var indexOfProject = baseUrl.indexOf('im-web');
	var indexOfHttp = baseUrl.indexOf('http://');
	var host = baseUrl.substring(indexOfHttp + 7, indexOfProject - 1);
	console.log(host);
	var wsuri = "ws://" + host + "/im-web/websocket";
	var ws = null;
	var selfSessionId = -1;
	var toId = -1;
	var defaults = {
			blockStyle:{
				color:'black',			//遮罩层默认颜色
				opacity:0				//遮罩层默认透明度（0：透明，1：不透明）
			},
			closeable:true,				//点击遮罩层是否可关闭弹出层，true:可关闭，false:不可关闭
			fadeTime:0,					//弹出层渐变时间
			marginTop:-1,				//弹出层距离顶部高度，默认居中
			single:false,				//是否只显示一个浮层；true：此浮层只会单独显示，显示时隐藏其他浮层
			scroll:false,				//浮层是否和页面一起滚动；true：浮层随页面一起滚动，false：浮层固定
			blockView:false				//是否显示遮罩层；true：显示（默认）
		};
	
	$(function() {
		startWebSocket();
	});
	function startWebSocket() {
		if ('WebSocket' in window)
			ws = new WebSocket(wsuri);
		else if ('MozWebSocket' in window)
			ws = new MozWebSocket(wsuri);
		else
			console.log("not support");

		ws.onmessage = function(evt) {
			var msg = createMessage(evt);
			console.log("message", msg);
			if (msg) {
				if (msg.fromUserType == 2) {// 系统消息 
					if(msg.messageType == 3 && msg.actionType == 1) {//用户自身的信息 
						selfSessionId = msg.sessionId;
						$('#fromId').html(selfSessionId);
						
						var userListIds = msg.otherSessionIds;
						if(userListIds) {
							for(var i = 0, len = userListIds.length; i < len; i ++) {
								addNewUserToList(userListIds[i]);
							}
						}
					}
				} else if (msg.fromUserType == 1 && selfSessionId != msg.fromId) { //普通用户 
					if(msg.messageType == 3) {
						switch(msg.actionType) {
							case 1 : 
								addNewUserToList(msg.fromId);
								break;
							case 2 : 
								removeUserFromList(msg.sessionId);
								break;
							defaul : break;						
						}
					} else if(msg.messageType == 1) {
						appendMessage(msg.fromId, msg.messageContent);
						clickTOuser(msg.fromId);
					}
				}
			}
		};

		ws.onclose = function(evt) {
			var msg = createMessage(evt);
			console.log("close", msg);
			
			//removeUserToList
		};

		ws.onopen = function(evt) {
			var msg = createMessage(evt);
			console.log("open", msg);
		};
	}
	function createMessage(evt) {
		if (evt) {
			var data = evt.data;
			if (data && data.length > 0) {
				data = data.trim().replace('\n','');
				return eval('[' + data + ']')[0];
			}
		}
		return null;
	}
	function sendMsg(id, msg) {
		if (toId == null || toId - 0 < 0) {
			return;
		}
		msg = msg || $('#writeMsg').val();
		
		appendMessage(id, msg, selfSessionId);

		var msgObj = {};
		msgObj.fromId = selfSessionId;
		msgObj.toId = id || toId;
		msgObj.fromUserType = 1;
		msgObj.messageType = 1;
		msgObj.messageContent = msg;

		var msgObjString = objToString(msgObj);
		ws.send(msgObjString);
	}

	function appendMessage(id, s, fromId) {
		if (s) {
			s = s.trim().replace('\n','');
			if(s.length > 0) {
				showPrivateMessage(id, s, fromId);
			}
		}
	}
	
	//获取消息内容的html 
	function getMessageHtml(id, msg) {
		
		var html = '';
		html += 	'<div class="lineBox"><div class="line1">';
		
		if(id == selfSessionId) {
			html += 	'	<span class="nameo" style="color : green;">' + id + '（我）' + new Date().format('yyyy-MM-dd mm:HH:ss') + '</span>';
		} else {
			html += 	'	<span class="nameo">' + id + ' ' + new Date().format('yyyy-MM-dd mm:hh:ss') + '</span>';
		}
		
		html += 	'	<span class="timeo"> </span>';
		html += 	'</div>';
		html += 	'<div class="line_msg">';
		html += 	'<pre style="padding-left : 22px; margin-top: 2px; margin-bottom:0px;">' + msg;
		html += 	'</pre></div>';
		

//		html += 	'<div class="line_msg">';
//		html += 	'	<blockquote class="message-bubble"> ';
//		html += 	'		<pre style="padding-left : 22px; margin-top: 2px; margin-bottom:0px;">' + msg + '</pre>';
//		html += 	'	</blockquote> ';
//		html += 	'</div>';
		html += 	'</div>';
//		html += 	'';
		return html;
	}

	function objToString(obj) {
		console.log(obj, typeof obj);
		if (obj && typeof obj == 'object') {
			var s = '{';
			for ( var i in obj) {
				var value = obj[i];
				if (typeof value == 'object') {
					s += i + ': "' + objToString(value) + '",';
				} else {
					s += i + ':"' + value + '",';
				}
			}
			s += '}';
			return s;
		}
		return obj == null ? '{}' : obj;
	}
	
	function addNewUserToList(id) {
		var listObj = $('#userList');
		
		var div = '';
		div += '<div class="userListItem" id="userListItem_' + id + '" ondblclick="clickTOuser(\'' + id + '\');">';
		div += '';
		div += id;
		div += '';
		div += '</div>';
		listObj.append(div);
	}

	function removeUserFromList(id) {
		var obj = $('#userList #userListItem_' + id);
		console.log(obj.length);
		obj.remove();
	}
	
	//双击用户名 
	function clickTOuser(id) {
		toId = id;
		$('#toId').html(toId);
		
		createPrivateMessageDiv(toId);
	}

	//输入框焦点 
	function privateTextAreaFocus(u) {
		jQuery('#' + pmdID(u)).find('textarea.pmdTextarea').focus();
	}
	
	//创建私聊窗口 
	function showPrivateMessage(messageToId, msg, messageFromId) {

		messageFromId = messageFromId || messageToId;
		
		var h = getMessageHtml(messageFromId, msg);
		
		createPrivateMessageDiv(messageToId);

		var pmdMainDiv = $('#' + pmdID(messageToId));
		var msgDiv = pmdMainDiv.find('div.pmdMessageDiv');
		msgDiv.append(h);
		// 消息滚动 
		scrollPrivateToBottom(messageToId);
	}
	
	//窗口滚动 
	function scrollPrivateToBottom(u) {

		var pmdMainDiv = $('#' + pmdID(u));
		var msgDiv = pmdMainDiv.find('div.pmdMessageDiv');
		
		var outerDiv = pmdMainDiv.find('div.pmdMessageContainer');
		scrollBottom(msgDiv, outerDiv);
	}
	//每次收到新消息，消息列表框滚到底部 
	function scrollBottom(msgDiv, outerDiv) {

		outerDiv.scrollTop(msgDiv.height() + 2000);

		clearMessageDiv();
	}
	function clearMessageDiv() {

		var divs = $('#messageDiv').find('div.lineBox');
		
		if(divs.length > 200) {
			divs.slice(0, 100).remove();
		};
	}
	
	//创建私聊窗口；如果已存在，则忽略 
	function createPrivateMessageDiv(id) {
		
		var pmdMainDiv = jQuery('#' + pmdID(id));
		if(pmdMainDiv.length < 1) {
			var h = createPrivateMessage(id);
			jQuery('body').append(h);
			var thisBlock = jQuery('div#' + pmdID(id));
			thisBlock.easydrag();
			thisBlock.setHandler(pmdDragID(id));

			thisBlock.showPop(defaults);
			privateTextAreaFocus(id);
			
			/*
			createMinBar(u);
			openPrivateMessage(u);
			*/
		} else {
			//setStatus('ttt:'+pmdMainDiv.length); 
			var _maxIndex = maxIndex(100);
			pmdMainDiv.css('z-index', _maxIndex + 1);
		}
	}
	
	//私聊窗口id 
	function pmdID(u) {
		return id = 'pmd_' + u;
	}
	//窗口拖曳id 
	function pmdDragID(u) {
		return id = 'pmdDrag_' + u;
	}
	//最小化工具栏id 
	function pmdMinID(u) {
		return id = 'pmdminbar_' + u;
	}
	//创建私聊窗口
	function createPrivateMessage(u) {
		var html = '';
		html += '<div id="' + pmdID(u) + '" class="privateMessageDiv">';
		html += '<div class="pmdStatus" id="'+pmdDragID(u)+'">';
		html += '	<div class="pmdStatusText">';
		html += '' + u;
		html += '	</div>';
		html += '	<div style="float: right;padding-top : 8px;padding-right : 0px;">';
		html += '		<span class="boxOpration_min" onclick="pmdMin(\''+u+'\');">－</span>';
		html += '		<span class="boxOpration_close" onclick="pmdClose(\''+u+'\');">×</span>';
		html += '	</div>';
		html += '	</div>';
		html += '		<table class="pmdTable">';
		html += '		<tr>';
		html += '			<td height="290">';
		html += '				<div class="pmdMessageContainer">';
		html += '					<div class="pmdMessageDiv">';
		html += '					</div>';
		html += '				</div>';
		html += '			</td>';
		html += '		</tr>';
		html += '		<tr>';
		html += '			<td height="110">';
		html += '				<div class="pmdInput1">';
		html += '					<textarea  onkeyup="pmdOnkeyup(\''+u+'\', this, event);" class="pmdTextarea" cols="90"></textarea>';
		html += '				</div>';
		html += '			</td>';
		html += '		</tr>';
		html += '	</table>';
		html += '</div>';
		return html;
	}
	//私聊输入框键盘事件
	function pmdOnkeyup(toId, thisObj, e) {
		var kc = e.keyCode;
		var value = jQuery(thisObj).val();
		if(e.ctrlKey && e.keyCode == 13) {
			jQuery(thisObj).val(value + '\n');
		} else if(kc == 13) {
			sendMsg(toId, value);
			jQuery(thisObj).val('');
		}
		e.preventDefault();
	}
	
	//双击用户，新建私聊窗口
	function newPrivateMsg(u) {
		checkPrivateDiv(u);
	}

	//关闭私聊
	function pmdClose(u) {
		var thisBlock = jQuery('div#' + pmdID(u));
		thisBlock.remove();
		
		jQuery('#' + pmdMinID(u)).remove();
		jQuery('#messageInput').focus();
	}
	
	function maxIndex(index){
		
		var obj = jQuery('body');
		
		index = index || 0;
		
		//获取所有对象
		var childrens = obj.children();
		
		//当前z-index
		var cindex = index;
		
		//遍历对象
		for(var i = 0; i < childrens.length; i ++){
		
			var tempIndex = childrens.eq(i).css('z-index');
			
			//当遍历对象已设置z-index属性，且可以转换为数字，且大于当前z-index
			if(tempIndex != null && !isNaN(parseInt(tempIndex)) && parseInt(tempIndex) > parseInt(cindex)){
				
				cindex = parseInt(tempIndex);
			}
		}
		
		return cindex;
	}
	

	Date.prototype.format = function(format){ 
		var o = { 
			"M+" : this.getMonth()+1, //month 
			"d+" : this.getDate(), //day 
			"h+" : this.getHours(), //hour 
			"m+" : this.getMinutes(), //minute 
			"s+" : this.getSeconds(), //second 
			"q+" : Math.floor((this.getMonth()+3)/3), //quarter 
			"S" : this.getMilliseconds() //millisecond 
		};

		if(/(y+)/.test(format)) { 
			format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
		} 

		for(var k in o) { 
			if(new RegExp("("+ k +")").test(format)) { 
				format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); 
			} ;
		} 
		return format; 
	};
</script>
<style type="text/css">
body {
	margin : 0px;
	font-size :13px;
}
div.userListItem{
	line-height : 26px;
	padding-left : 10px;
	cursor : pointer;
	border-bottom : 1px solid #EFEFEF;
}
div.userListItem:hover{
	background-color : #EFEFEF;
}
div#userList{
	moz-user-select: -moz-none;
	-moz-user-select: none;
	-o-user-select:none;
	-khtml-user-select:none;
	-webkit-user-select:none;
	-ms-user-select:none;
	user-select:none;
}

div.privateMessageDiv {
	display: none;
	width : 500px;
	height : 443px;
	border : 1px solid #6AB6E7;
	border-radius : 4px;
	box-shadow: 
	  rgba(84, 171, 228, 0.85) 
	  1px  
	  1px  
	  3px; 
	background-color: rgba(156,207,240,0.8);
}
div.pmdStatus {
	height : 28px;
	padding-left : 10px;
}
div.pmdStatusText {
	padding-top : 8px;
	float : left;
	font-weight : bold;
}
table.pmdTable {
	border-collapse : collapse;
	width : 100%;
}
table.pmdTable td {
	
}
span[class^=boxOpration_] {
	font-weight : bold;
	color : white;
	cursor : pointer;
	padding-top : 7px;
	padding-bottom : 5px;
	padding-left : 14px;
	padding-right : 14px;
	border-radius : 4px;
	margin-right : 4px;
	margin-left : -5px;
}
span[class^=boxOpration_close]:hover {
	background-color: #F43B2C;
}
span[class^=boxOpration_min]:hover {
	background-color: #66B5E7;
}

div.lineBox {
	margin-top : 5px;
}

div.line1 {
	font-size : 13px;
	padding : 2px;
	color : blue;
	margin-top : 0px;
	margin-bottom : -2px;
}

.pmdTextarea {
	margin-left:3px; 
	border : 1px solid #73B8E2;
	background-color: rgba(255,255,255,0.8);
	resize: none;
	overflow : auto;
	width:482px;
	padding:4px;
	height : 107px;
}
div.pmdMessageContainer {
	margin-left : 3px;
	width : 485px;
	height : 285px;
	border : 1px solid #73B8E2;
	overflow : auto;
	padding-left : 5px;
	background-color: rgba(255,255,255,0.8);
}
div.pmdMessageDiv {
	padding-top : 0px;
	padding-bottom : 5px;
	padding-right : 3px;
	overflow-x : hidden;
	overflow-y : auto;
}
div.line_msg {
	font-size : 13px;
	padding : 1px auto 0px auto;
	word-wrap: break-word; 
	word-break: normal;
	color : black;
}
div.line_msg p {
	margin-top : 0px;
	margin-bottom : 0px;
}
span.nameo {
	padding-right : 5px;
}
span.timeo {
	padding-left : 5px;
}
</style>
</head>
<body>
<div>
	<div style="width : 90%; height : 30px; padding-left : 20px; line-height : 25px;">
		<div >
			当前用户ID：<span id="fromId"></span> ---》
			目标用户ID：<span id="toId"></span>
		</div>
	</div>
	<div>
		<table>
			<tr>
				<td>
					<div style=" border : 0px solid gray; 
					width : 220px; height : 500px; padding-top : 0px; padding-bottom : 0px;
					box-shadow : 1px 1px 8px black;
					border-radius : 2px;
					
					">
						<div id="userList" style="background-color : white;">
						</div>
					</div>
				</td>
				<td>

				</td>
			</tr>
		</table>
	</div>
</div>
</body>
</html>
